const db = require('../config/database');

class Comment {
    static async create({ news_id, user_id, content }) {
        try {
            console.log('Creating comment:', { news_id, user_id, content });
            const [result] = await db.query(
                'INSERT INTO comments (news_id, user_id, content) VALUES (?, ?, ?)',
                [news_id, user_id, content]
            );
            return this.findById(result.insertId);
        } catch (error) {
            console.error('创建评论失败:', error);
            throw error;
        }
    }

    static async findById(id) {
        try {
            console.log('Finding comment by ID:', id);
            const [rows] = await db.query(
                `SELECT c.*, u.username 
                FROM comments c 
                LEFT JOIN users u ON c.user_id = u.user_id 
                WHERE c.comment_id = ?`,
                [id]
            );
            console.log('Found comment:', rows[0]);
            return rows[0];
        } catch (error) {
            console.error('查找评论失败:', error);
            throw error;
        }
    }

    static async getByNewsId(newsId) {
        try {
            console.log('Getting comments for news ID:', newsId);
            const [rows] = await db.query(
                `SELECT c.*, u.username 
                FROM comments c 
                LEFT JOIN users u ON c.user_id = u.user_id 
                WHERE c.news_id = ? 
                ORDER BY c.created_at DESC`,
                [newsId]
            );
            console.log('Found comments:', rows);
            return rows;
        } catch (error) {
            console.error('获取评论列表失败:', error);
            throw error;
        }
    }

    static async delete(id) {
        try {
            console.log('Deleting comment:', id);
            await db.query('DELETE FROM comments WHERE comment_id = ?', [id]);
            return true;
        } catch (error) {
            console.error('删除评论失败:', error);
            throw error;
        }
    }

    static async updateLikes(id) {
        try {
            console.log('Updating likes for comment:', id);
            await db.query(
                'UPDATE comments SET likes = likes + 1 WHERE comment_id = ?',
                [id]
            );
            return true;
        } catch (error) {
            console.error('更新评论点赞数失败:', error);
            throw error;
        }
    }

    static async hasLiked(commentId, userId) {
        try {
            const [rows] = await db.query(
                'SELECT COUNT(*) as count FROM comment_likes WHERE comment_id = ? AND user_id = ?',
                [commentId, userId]
            );
            return rows[0].count > 0;
        } catch (error) {
            console.error('检查评论点赞状态失败:', error);
            throw error;
        }
    }

    static async like(commentId, userId) {
        try {
            // First check if the like already exists
            const hasLiked = await this.hasLiked(commentId, userId);
            if (hasLiked) {
                return false;
            }

            // Add the like
            await db.query(
                'INSERT INTO comment_likes (comment_id, user_id, created_at) VALUES (?, ?, NOW())',
                [commentId, userId]
            );

            // Update the likes count
            await db.query(
                'UPDATE comments SET likes = likes + 1 WHERE comment_id = ?',
                [commentId]
            );

            return true;
        } catch (error) {
            console.error('点赞评论失败:', error);
            throw error;
        }
    }

    static async unlike(commentId, userId) {
        try {
            // First check if the like exists
            const hasLiked = await this.hasLiked(commentId, userId);
            if (!hasLiked) {
                return false;
            }

            // Remove the like
            await db.query(
                'DELETE FROM comment_likes WHERE comment_id = ? AND user_id = ?',
                [commentId, userId]
            );

            // Update the likes count
            await db.query(
                'UPDATE comments SET likes = GREATEST(likes - 1, 0) WHERE comment_id = ?',
                [commentId]
            );

            return true;
        } catch (error) {
            console.error('取消点赞评论失败:', error);
            throw error;
        }
    }

    static async getLikeCount(commentId) {
        try {
            const [rows] = await db.query(
                'SELECT COUNT(*) as count FROM likes WHERE type = ? AND comment_id = ?',
                ['comment', commentId]
            );
            return rows[0].count;
        } catch (error) {
            console.error('获取评论点赞数失败:', error);
            throw error;
        }
    }

    static async hasUserLiked(commentId, userId) {
        try {
            const [rows] = await db.query(
                'SELECT COUNT(*) as count FROM likes WHERE type = ? AND comment_id = ? AND user_id = ?',
                ['comment', commentId, userId]
            );
            return rows[0].count > 0;
        } catch (error) {
            console.error('检查用户点赞状态失败:', error);
            throw error;
        }
    }

    static async getCommentsWithLikeStatus(newsId, userId) {
        try {
            const [comments] = await db.query(
                `SELECT c.*, 
                    (SELECT COUNT(*) FROM likes WHERE type = 'comment' AND comment_id = c.comment_id) as likes,
                    (SELECT COUNT(*) FROM likes WHERE type = 'comment' AND comment_id = c.comment_id AND user_id = ?) as is_liked
                FROM comments c
                WHERE c.news_id = ?
                ORDER BY c.created_at DESC`,
                [userId, newsId]
            );
            return comments.map(comment => ({
                ...comment,
                is_liked: comment.is_liked > 0
            }));
        } catch (error) {
            console.error('获取评论列表失败:', error);
            throw error;
        }
    }
}

module.exports = Comment; 